<?php
/**
 * Created by PhpStorm.
 * UserController: 86158
 * Date: 2020/8/1
 * Time: 14:06
 */

namespace app\merchant\controller\shop;

use app\http\validates\user\RegisterValidates;
use app\merchant\controller\AuthController;
use app\models\shop\MerchantAdmin;
use app\models\user\UserToken;
use app\Request;
use crmeb\services\UtilService;
use crmeb\services\UtilService as Util;
use crmeb\traits\JwtAuthModelTrait;
use JPush\Client;
use think\exception\ValidateException;

class User
{
    use JwtAuthModelTrait;
    /**
     * 注册
     * @param Request $request
     * @return mixed
     */
    public function register(Request $request)
    {
        list($account, $password, $captcha) = UtilService::postMore([['account', ''], ['password', ''], ['captcha', '654321']], $request, true);
        try {
            validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'password' => $password ,'captcha' => $captcha,]);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
            return app('json')->fail('密码必须是在6到16位之间');
        if ($password == '123456') return app('json')->fail('密码太过简单，请输入较为复杂的密码');
        $registerStatus = MerchantAdmin::register($account, $password);
        if ($registerStatus) return app('json')->success('注册成功');
        return app('json')->fail(MerchantAdmin::getErrorInfo('注册失败'));
    }

    /**
     * 登录
     * @param Request $request
     * @return mixed
     */
    public function login()
    {
        $data = Util::postMore([
            ['account', ''],
            ['password', ''],
            ['push_id', ''],
        ]);
        $user = MerchantAdmin::where('account', $data['account'])->find();
        if ($user) {
            if ($user->pwd !== md5($data['password']))
                return app('json')->fail('账号或密码错误');
        } else {
            return app('json')->fail('账号或密码错误');
        }
        $token = AuthController::getToken($user);
        if ($token) {
            $push_id = $data['push_id'];
            if ($push_id){
                $user->push_id = $push_id;
                $user->save();
            }
            return app('json')->success('登录成功', ['token' => $token['token'], 'info' => $user]);
        } else
            return app('json')->fail('登录失败');
    }

    public function j_push()
    {
        j_push("test",MerchantAdmin::where('id',1)->find()->push_id);
    }

}